//
//  CategoryViewController.m
//  jang
//
//  Created by lee han on 04/04/2017.
//  Copyright © 2017 lee han. All rights reserved.
//

#import "CategoryViewController.h"
#import "CommonView.h"
#import "UIView+UIViewExt.h"
#import "UIImageView+WebCache.h"
#import "CategoryCell.h"
#import "ProductListController.h"

@interface CategoryViewController (){
    NSInteger mCurrentIndex;
}
-(void)getCategoryInfo;
-(void)onCategoryGetted:(NSArray*) data;
-(void)setCategoryScrollView;
-(void)setTabViewInfo:(NSInteger)index;

@end

@implementation CategoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    [CommonView setNativationBar:self];
    
    UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [rightButton setImage:[UIImage imageNamed:@"search.png"] forState:UIControlStateNormal];
    
    [rightButton addTarget:self action:@selector(onClickSearch) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = barButtonItem;
    
    
    _mSearchText.delegate = self;
    
    mCurrentIndex = -1;
    
    [_mTableView registerNib:[UINib nibWithNibName:@"CategoryCell" bundle:nil] forCellReuseIdentifier:@"CategoryCell"];
    _mTableView.delegate = self;
    _mTableView.dataSource = self;
    
    mButtons = [[NSMutableArray alloc] init];
    [self getCategoryInfo];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)onClickSearch {
    [self performSegueWithIdentifier:@"tosearch" sender:self];
}

-(void)getCategoryInfo{
    NSMutableDictionary* data = [[NSMutableDictionary alloc] init];
    
    [[network sharedInstance] startHttpRequest:self Data:data functionType:NetworkFunctionType_CategoryList];
}

-(void)onCategoryGetted:(NSArray*) data{
    mCategoryData = data;
    
    [self setCategoryScrollView];
    [self setTabViewInfo:0];
}

-(void)setCategoryScrollView{
    if(mCategoryData == nil)
        return;
    
    float scrollheight = 0;
    for( int i=0; i<mCategoryData.count; i++){
        
        CategoryButtonView* buttonview = [CategoryButtonView loadFromNib];
        buttonview.mIndex = i;
        buttonview.mDelegate = self;
        buttonview.mText.text = [[mCategoryData objectAtIndex:i] objectForKey:@"name"];
        NSString* urlstr = [URLIMAGE_PRE stringByAppendingString:[[mCategoryData objectAtIndex:i] objectForKey:@"path"]];
        [buttonview.mImage sd_setImageWithURL:[NSURL URLWithString:urlstr] placeholderImage:[UIImage imageNamed:@"wenhao.png"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            buttonview.mImage.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        }];
        [buttonview.mImage setTintColor:[UIColor grayColor]];
        CGRect r = buttonview.frame;
        r.origin.y = i * CategoryButtonHeight + i;
        buttonview.frame = r;
        if(i == mCategoryData.count - 1)
            scrollheight = r.origin.y + CategoryButtonHeight;
        [_mScrollView addSubview: buttonview];
        
        [mButtons addObject:buttonview];
    }
    
    CGRect sr = _mScrollView.frame;
    if(sr.size.height < scrollheight){
        sr.size.height = scrollheight;
        _mScrollView.contentSize = sr.size;
    }
    [[mButtons objectAtIndex:0] setHighLight:TRUE];
}

-(void)setTabViewInfo:(NSInteger)index{
    if(mCurrentIndex == index)
        return;
    mCurrentIndex = index;
    [_mTableView reloadData];
}

#pragma mark networkDelegate

- (void)parserResult:(NSDictionary *)response functionType:(NSInteger)type
{
    if(type == NetworkFunctionType_CategoryList){
        if([[response objectForKey:@"status"] integerValue] == 1){
            [self onCategoryGetted:[response objectForKey:@"data"]];
        }
        else{
            [CommonView addAlertView:self Text:@"类别错误"];
        }
    }
    else if (type == NetworkFunctionType_ProductList || type == NetworkFunctionType_BurstSectionList || type == NetworkFunctionType_search){
        if([[response objectForKey:@"status"] integerValue] == 1){
            mProductListData = response;
            [self performSegueWithIdentifier:@"categerytopl" sender:self];
        }
        else{
            [CommonView addAlertView:self Text:@"产品列表错误"];
        }
    }
}
//end networkDelegate

#pragma mark CategoryButtonDelegate
- (void)onClickCategoryButton:(NSInteger)index{
    for(int i = 0; i < mButtons.count; ++i){
        [[mButtons objectAtIndex:i] setHighLight:i==index];
    }
    [self setTabViewInfo:index];
}
//end CategoryButtonDelegate

#pragma mark UITableViewDelegate
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel* lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    lable.backgroundColor = [UIColor clearColor];
    lable.text = [[[[mCategoryData objectAtIndex:mCurrentIndex] objectForKey:@"children"] objectAtIndex:section] objectForKey:@"name"];
    return lable;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
//end UITableViewDelegate

#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [[[mCategoryData objectAtIndex:mCurrentIndex] objectForKey:@"children"] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger count = [[[[[mCategoryData objectAtIndex:mCurrentIndex] objectForKey:@"children"] objectAtIndex:section] objectForKey:@"children"] count];
    return count / 3 + (count % 3 > 0 ? 1 : 0);
    return count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CategoryCell *cell = [_mTableView dequeueReusableCellWithIdentifier:@"CategoryCell" forIndexPath:indexPath];
    NSArray* cellinfo = [[[[mCategoryData objectAtIndex:mCurrentIndex] objectForKey:@"children"] objectAtIndex:indexPath.section] objectForKey:@"children"];
    
    cell.mButton2.hidden = cell.mButton3.hidden = YES;
    
    NSInteger index = indexPath.row * 3;
    cell.mButton1.mText.text = [[cellinfo objectAtIndex:index] objectForKey:@"name"];
    NSString* urlstr = [URLIMAGE_PRE stringByAppendingString:[[cellinfo objectAtIndex:index] objectForKey:@"path"]];
    [cell.mButton1.mImageView sd_setImageWithURL:[NSURL URLWithString:urlstr] placeholderImage:[UIImage imageNamed:@"wenhao.png"]];
    cell.mButton1.mCategoryID = [[[cellinfo objectAtIndex:index] objectForKey:@"id"] integerValue];
    cell.mButton1.mDelegate = self;
    
    ++index;
    if(index >= [cellinfo count])
        goto end;
    cell.mButton2.hidden = NO;
    cell.mButton2.mText.text = [[cellinfo objectAtIndex:index] objectForKey:@"name"];
    urlstr = [URLIMAGE_PRE stringByAppendingString:[[cellinfo objectAtIndex:index] objectForKey:@"path"]];
    [cell.mButton2.mImageView sd_setImageWithURL:[NSURL URLWithString:urlstr] placeholderImage:[UIImage imageNamed:@"wenhao.png"]];
    cell.mButton2.mCategoryID = [[[cellinfo objectAtIndex:index] objectForKey:@"id"] integerValue];
    cell.mButton2.mDelegate = self;
    
    ++index;
    if(index >= [cellinfo count])
        goto end;
    cell.mButton3.hidden = NO;
    cell.mButton3.mText.text = [[cellinfo objectAtIndex:index] objectForKey:@"name"];
    urlstr = [URLIMAGE_PRE stringByAppendingString:[[cellinfo objectAtIndex:index] objectForKey:@"path"]];
    [cell.mButton3.mImageView sd_setImageWithURL:[NSURL URLWithString:urlstr] placeholderImage:[UIImage imageNamed:@"wenhao.png"]];
    cell.mButton3.mCategoryID = [[[cellinfo objectAtIndex:index] objectForKey:@"id"] integerValue];
    cell.mButton3.mDelegate = self;
    
end:
    return cell;
}



//end UITableViewDataSource

#pragma mark CategoryCellButtonDelegate
-(void)onClickCategoryCellButton:(NSInteger)cid{
    
    NSMutableDictionary* data = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld", (long)cid], @"categoryid", nil];
    
    [[network sharedInstance] startHttpRequest:self Data:data functionType:NetworkFunctionType_ProductList];
    
}
//end CategoryCellButtonDelegate

#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if(textField.text.length == 0){
        return NO;
    }
    [textField resignFirstResponder];
    NSMutableDictionary* data = [NSMutableDictionary dictionaryWithObjectsAndKeys:textField.text, @"search", nil];
    
    [[network sharedInstance] startHttpRequest:self Data:data functionType:NetworkFunctionType_search];
    return YES;
}
//end UITextFieldDelegate

- (void)prepareForSegue: (UIStoryboardSegue *)segue sender:(id)sender{
    ProductListController *destination = segue.destinationViewController;
    
    destination.mCategoryID = [[mProductListData objectForKey:@"id"] integerValue];
    destination.mTitle = [mProductListData objectForKey:@"name"];
    destination.mMaxPage = [[mProductListData objectForKey:@"page"] integerValue];
    destination.mListData = [mProductListData objectForKey:@"data"];
    destination.mSearchString = [mProductListData objectForKey:@"search"];
}

- (IBAction)onClickBurstSection:(id)sender {
    
    NSMutableDictionary* data = [[NSMutableDictionary alloc] init];
    
    [[network sharedInstance] startHttpRequest:self Data:data functionType:NetworkFunctionType_BurstSectionList];
}
@end
